package main

import (
	"fmt"
	"strings"
)

func main() {
	toEnvMapTest()


	/*
		var countryCapitalMap map[string]string
		countryCapitalMap["France"] = "Paris"
		countryCapitalMap["China"] = "Beijing"
		fmt.Println("字典：", countryCapitalMap)
		//这样写会崩溃的，报错：panic: assignment to entry in nil map
		//结论：nil map不能用来存放键值对的
	*/

	/*
	var count int
	count = 99
	fmt.Println("count的值：", count)
	
	var countryCapitalMap map[string]string = make(map[string]string)
	countryCapitalMap["France"] = "Paris"
	countryCapitalMap["China"] = "Beijing"
	//fmt.Println("字典：", countryCapitalMap)
	
	//字典的遍历
	for country, city := range countryCapitalMap {
		fmt.Println("国家：", country, "城市：", city)
	}
	
	//查看元素在集合中是否存在
	city, isFind := countryCapitalMap["China"]
	fmt.Println("找到key:", isFind)
	if isFind {
		fmt.Println("找到key——China对应的value:", city)
	} else {
		fmt.Println("没有找到key")
	}
	*/
}

func toEnvMapTest()  {
	EnvironmnetStr := "XNEO_LONG_JSON=1"
	environment := strings.Split(EnvironmnetStr,"\n")

	var envmap = make(map[string]string)
	envmap["XNEO_AI_XUAN"] = "1"
	ToEnvMap(environment,&envmap)
	fmt.Println("最后字典是是：",envmap)
}

func ToEnvMap(custom []string, envMap *map[string]string) {
	var customMap = make(map[string]string)
	for _, v := range custom {
		// 找=号位置
		idx := strings.Index(v, "=")
		if idx == -1 {
			continue
		}
		fmt.Println("for循环找到的索引是：",idx)
		// 取出key和value
		key := v[:idx]
		value := v[idx+1:]

		fmt.Println("for循环key是：",key,"value值是：",value)

		// 判断是否为空
		if key == "" || value == "" {
			continue
		}
		// 如果value中还有=则舍弃
		idx = strings.Index(value, "=")
		if idx != -1 {
			continue
		}

		// 合并相同key的env
		if customMap[key] != "" {
			if customMap[key] != value {
				customMap[key] = customMap[key] + ";" + value
			}
		} else {
			customMap[key] = value
		}
	}

	for k, v := range customMap {
		// 相同key的env不再添加
		if (*envMap)[k] != "" {
			continue
		}

		(*envMap)[k] = v
	}
}